import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { GameState, Player, Item, Equipment, Skill, Quest, Realm } from '@/types/game';
import { db, initializeGameData } from '@/lib/database';
import { resetDatabase } from '@/lib/database-reset';

interface GameStore extends GameState {
  // 玩家相关
  createPlayer: (name: string) => Promise<void>;
  updatePlayer: (updates: Partial<Player>) => void;
  gainExperience: (amount: number) => Promise<void>;
  breakthrough: () => Promise<boolean>;
  addGold: (amount: number) => void;
  
  // 物品相关
  addItem: (item: Item, quantity: number) => void;
  removeItem: (itemId: string, quantity: number) => void;
  equipItem: (item: Item) => void;
  unequipItem: (slot: keyof Equipment) => void;
  
  // 技能相关
  learnSkill: (skill: Skill) => void;
  upgradeSkill: (skillId: string) => void;
  
  // 任务相关
  acceptQuest: (quest: Quest) => void;
  completeQuest: (questId: string) => void;
  updateQuestProgress: (questId: string, progress: number) => void;
  checkQuestProgress: () => void;
  
  // 游戏初始化
  initializeGame: () => Promise<void>;
  
  // 设置相关
  updateSettings: (settings: Partial<GameState['settings']>) => void;
}

const createDefaultPlayer = (): Player => ({
  id: 'player-1',
  name: '无名修士',
  level: 1,
  realm: {
    id: 'qi-refining',
    name: '练气期',
    level: 1,
    description: '修仙入门境界，炼化天地灵气',
    requiredExp: 0,
    bonusStats: { health: 100, mana: 50, attack: 10, defense: 5, speed: 5 }
  },
  experience: 0,
  maxExperience: 100, // 1级需要100经验
  health: 100,
  maxHealth: 100,
  mana: 50,
  maxMana: 50,
  attack: 10,
  defense: 5,
  speed: 5,
  gold: 1000,
  avatar: '🧙‍♂️',
  createdAt: new Date(),
  lastLoginAt: new Date()
});

export const useGameStore = create<GameStore>()(
  persist(
    (set, get) => ({
      // 初始状态
      player: createDefaultPlayer(),
      inventory: [],
      equipment: {},
      skills: [],
      quests: [],
      gold: 1000,
      settings: {
        soundEnabled: true,
        musicEnabled: true,
        autoSave: true
      },

      // 玩家相关方法
      createPlayer: async (name: string) => {
        const player = createDefaultPlayer();
        player.name = name;
        player.id = `player-${Date.now()}`;
        player.maxExperience = 100; // 确保有maxExperience字段
        
        await db.players.add(player);
        set({ player });
      },

      updatePlayer: (updates) => {
        set((state) => ({
          player: { ...state.player, ...updates }
        }));
      },

      gainExperience: async (amount: number) => {
        const state = get();
        const calculateMaxExperience = (level: number) => {
          return Math.floor(100 * Math.pow(1.5, level - 1));
        };
        
        let newExp = state.player.experience + amount;
        let newLevel = state.player.level;
        let levelUps = 0;
        
        // 检查升级，确保经验值不会无限增长
        while (newExp >= calculateMaxExperience(newLevel) && newLevel < 100) {
          const currentLevelMaxExp = calculateMaxExperience(newLevel);
          newExp -= currentLevelMaxExp;
          newLevel++;
          levelUps++;
          
          // 如果达到100级，经验值不能超过当前等级上限
          if (newLevel >= 100) {
            newLevel = 100;
            const maxExpFor100 = calculateMaxExperience(100);
            newExp = Math.min(newExp, maxExpFor100 - 1);
            break;
          }
        }
        
        // 如果没有升级，确保经验不超过当前等级上限
        if (levelUps === 0) {
          const currentMaxExp = calculateMaxExperience(state.player.level);
          newExp = Math.min(newExp, currentMaxExp - 1);
        }
        
        set((state) => ({
          player: { 
            ...state.player, 
            experience: newExp,
            level: newLevel,
            maxExperience: calculateMaxExperience(newLevel)
          }
        }));
      },

      breakthrough: async () => {
        const state = get();
        const realms = await db.realms.orderBy('level').toArray();
        const nextRealm = realms.find(r => r.level === state.player.realm.level + 1);
        
        if (!nextRealm || state.player.experience < nextRealm.requiredExp) {
          return false;
        }

        // 突破成功
        const bonusStats = nextRealm.bonusStats;
        set((state) => ({
          player: {
            ...state.player,
            realm: nextRealm,
            level: state.player.level + 1,
            maxHealth: state.player.maxHealth + bonusStats.health,
            health: state.player.health + bonusStats.health,
            maxMana: state.player.maxMana + bonusStats.mana,
            mana: state.player.mana + bonusStats.mana,
            attack: state.player.attack + bonusStats.attack,
            defense: state.player.defense + bonusStats.defense,
            speed: state.player.speed + bonusStats.speed
          }
        }));

        return true;
      },

      addGold: (amount) => {
        set((state) => ({
          gold: state.gold + amount
        }));
      },

      // 物品相关方法
      addItem: (item, quantity) => {
        set((state) => {
          const existingIndex = state.inventory.findIndex(inv => inv.item.id === item.id);
          
          if (existingIndex >= 0 && item.stackable) {
            const newInventory = [...state.inventory];
            newInventory[existingIndex].quantity += quantity;
            return { inventory: newInventory };
          } else {
            return {
              inventory: [...state.inventory, { item, quantity }]
            };
          }
        });
      },

      removeItem: (itemId, quantity) => {
        set((state) => {
          const newInventory = state.inventory
            .map(inv => 
              inv.item.id === itemId 
                ? { ...inv, quantity: inv.quantity - quantity }
                : inv
            )
            .filter(inv => inv.quantity > 0);
          
          return { inventory: newInventory };
        });
      },

      equipItem: (item) => {
        set((state) => {
          const newEquipment = { ...state.equipment };
          
          if (item.type === 'weapon') {
            newEquipment.weapon = item;
          } else if (item.type === 'armor') {
            newEquipment.armor = item;
          } else if (item.type === 'accessory') {
            newEquipment.accessory = item;
          }
          
          return { equipment: newEquipment };
        });
      },

      unequipItem: (slot) => {
        set((state) => {
          const newEquipment = { ...state.equipment };
          delete newEquipment[slot];
          return { equipment: newEquipment };
        });
      },

      // 技能相关方法
      learnSkill: (skill) => {
        set((state) => ({
          skills: [...state.skills, skill]
        }));
      },

      upgradeSkill: (skillId) => {
        set((state) => ({
          skills: state.skills.map(skill =>
            skill.id === skillId && skill.level < skill.maxLevel
              ? { ...skill, level: skill.level + 1 }
              : skill
          )
        }));
      },

      // 任务相关方法
      acceptQuest: (quest) => {
        set((state) => ({
          quests: [...state.quests, { ...quest, status: 'active' as const }]
        }));
      },

      completeQuest: (questId) => {
        set((state) => ({
          quests: state.quests.map(quest =>
            quest.id === questId
              ? { ...quest, status: 'completed' as const }
              : quest
          )
        }));
      },

      updateQuestProgress: (questId, progress) => {
        set((state) => ({
          quests: state.quests.map(quest =>
            quest.id === questId
              ? { ...quest, progress }
              : quest
          )
        }));
      },

      checkQuestProgress: () => {
        const state = get();
        const updatedQuests = state.quests.map(quest => {
          if (quest.status !== 'active') return quest;

          let newProgress = quest.progress;

          // 根据任务类型检查进度
          switch (quest.id) {
            case 'main-001': // 初入修仙路 - 完成修炼
              if (state.player.experience > 0) {
                newProgress = 1;
              }
              break;
            
            case 'daily-001': // 每日修炼 - 完成3次修炼
              // 这里可以添加修炼次数统计逻辑
              break;
            
            case 'main-002': // 首次战斗 - 击败敌人
              // 这里可以添加战斗胜利统计
              break;
            
            case 'side-002': // 境界突破
              if (state.player.realm.level >= 1) {
                newProgress = 1;
              }
              break;
          }

          return { ...quest, progress: newProgress };
        });

        set({ quests: updatedQuests });
      },

      // 游戏初始化
      initializeGame: async () => {
        try {
          await initializeGameData();
          
          // 加载初始技能
          const skills = await db.skills.where('requiredRealm').equals(1).toArray();
          
          // 添加一些初始物品供测试
          const initialItems = await db.items.toArray();
          const inventory = initialItems.slice(0, 3).map(item => ({
            item,
            quantity: item.stackable ? Math.floor(Math.random() * 5) + 1 : 1
          }));
          
          set({ skills, inventory });
        } catch (error) {
          console.error('数据库初始化失败:', error);
          
          // 如果是索引错误，尝试重置数据库
          if (error instanceof Error && error.message.includes('KeyPath')) {
            console.log('检测到数据库索引错误，正在重置数据库...');
            try {
              await resetDatabase();
              // 重新初始化
              await initializeGameData();
              const skills = await db.skills.where('requiredRealm').equals(1).toArray();
              const initialItems = await db.items.toArray();
              const inventory = initialItems.slice(0, 3).map(item => ({
                item,
                quantity: item.stackable ? Math.floor(Math.random() * 5) + 1 : 1
              }));
              set({ skills, inventory });
              console.log('数据库重置成功！');
            } catch (resetError) {
              console.error('数据库重置失败:', resetError);
              // 使用默认数据
              set({ skills: [], inventory: [] });
            }
          } else {
            // 其他错误，使用默认数据
            set({ skills: [], inventory: [] });
          }
        }
      },

      // 设置相关
      updateSettings: (settings) => {
        set((state) => ({
          settings: { ...state.settings, ...settings }
        }));
      },

      // 计算等级所需最大经验值
      calculateMaxExperience: (level: number) => {
        return Math.floor(100 * Math.pow(1.5, level - 1));
      }
    }),
    {
      name: 'cultivation-game-storage',
      version: 1
    }
  )
);